﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kangsuce.Common;
using kangsuce.Model;
using Newtonsoft.Json;

namespace kangsuce.Admin.Controllers
{
    public class SaleController : BaseController
    {
        private BLL.GoodsBLL goodsBLL = new BLL.GoodsBLL();
        private BLL.VideoBLL videoBLL = new BLL.VideoBLL();

        /// <summary>
        /// 商品列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GoodsList()
        {
            return View();
        }

        /// <summary>
        /// 获取商品列表数据
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult GetGoodsList(int pageSize, int pageNumber, string name = "")
        {
            try
            {
                int total;
                var list = goodsBLL.GetListByPage(pageSize, pageNumber, out total,
                    p => name == "" || (p.goodsTitle.Contains(name)),
                    c => c.OrderBy(p => p.goodsId));
                return Json(new {rows = list, total = total}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 商品编辑
        /// </summary>
        /// <param name="id">商品id</param>
        /// <returns></returns>
        public ActionResult GoodsEdit(int id = 0)
        {
            KSC_Goods model = goodsBLL.GetModelById(id) ??
                              new KSC_Goods {goodsId = 0, goodsFilePath = "/Content/img/default.jpg"};
            ViewBag.Json = JsonConvert.SerializeObject(model);
            return View();
        }

        /// <summary>
        /// 商品保存
        /// </summary>
        /// <returns></returns>
        public ActionResult GoodsSave()
        {
            try
            {
                int goodsId = Convert.ToInt32(Request.Form["goodsId"] ?? "0");
                string goodsFilePath = System.Web.HttpUtility.UrlDecode(Request.Form["goodsFilePath"] ?? ""); //商品图片
                string goodsSummary = System.Web.HttpUtility.UrlDecode(Request.Form["goodsSummary"] ?? ""); //商品简介
                string goodsTitle = System.Web.HttpUtility.UrlDecode(Request.Form["goodsTitle"] ?? ""); //商品标题
                string goodsUrl = System.Web.HttpUtility.UrlDecode(Request.Form["goodsUrl"] ?? ""); //商品链接

                if (goodsId == 0)
                {
                    KSC_Goods model = new KSC_Goods
                    {
                        goodsFilePath = goodsFilePath,
                        goodsSummary = goodsSummary,
                        goodsTitle = goodsTitle,
                        goodsUrl = goodsUrl
                    };
                    goodsId = goodsBLL.Insert(model);
                    return Json(new {result = goodsId > 0 ? "success" : "error", msg = goodsId > 0 ? "新增成功" : "新增失败"});
                }
                else
                {
                    KSC_Goods model = goodsBLL.GetModelById(goodsId);
                    model.goodsFilePath = goodsFilePath;
                    model.goodsSummary = goodsSummary;
                    model.goodsTitle = goodsTitle;
                    model.goodsUrl = goodsUrl;
                    bool result = goodsBLL.Update(model);
                    return Json(new {result = result ? "success" : "error", msg = result ? "修改成功" : "修改失败"});
                }
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message});
            }
        }

        /// <summary>
        /// 商品删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult GoodsDelete(string ids = "")
        {
            try
            {
                if (ids == "")
                {
                    return Json(new {result = "error", msg = "传入参数有误"}, JsonRequestBehavior.AllowGet);
                }
                List<int> idList =
                    ids.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(item => item.ToInt32()).ToList();
                var result = goodsBLL.Delete(idList, Server.MapPath("/Upload"));
                return Json(new {result = result ? "success" : "error", msg = result ? "删除成功" : "删除失败"},
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 视频列表
        /// </summary>
        /// <returns></returns>
        public ActionResult VideoList()
        {
            return View();
        }

        /// <summary>
        /// 获取视频列表数据
        /// </summary>
        /// <param name="pageSize">分页大小</param>
        /// <param name="pageNumber">页码</param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult GetVideoList(int pageSize, int pageNumber, string name = "")
        {
            try
            {
                int total;
                var list = videoBLL.GetListByPage(pageSize, pageNumber, out total,
                    p => name == "" || p.videoName.Contains(name),
                    c => c.OrderBy(p => p.videoId));
                return Json(new { rows = list, total = total }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { result = "error", msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 视频编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult VideoEdit(int id=0)
        {
            KSC_Video model = videoBLL.GetModelById(id) ??
                              new KSC_Video {videoId = 0, imgPath = "/Content/img/default.jpg"};
            ViewBag.Json = JsonConvert.SerializeObject(model);
            return View();
        }

        /// <summary>
        /// 视频保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult VideoSave(KSC_Video model)
        {
            try
            {
                int videoId = Request.Form["videoId"].ToInt32();
                if (videoId == 0)
                {
                    model.filePath = HttpUtility.UrlDecode(model.filePath);//文件路径
                    model.imgPath = HttpUtility.UrlDecode(model.imgPath);//封面路径
                    model.videoName = HttpUtility.UrlDecode(model.videoName);//视频标题
                    videoId = videoBLL.Insert(model);
                    return Json(new { result = videoId > 0 ? "success" : "error", msg = videoId > 0 ? "新增成功" : "新增失败" });
                }
                else
                {
                    KSC_Video editModel = videoBLL.GetModelById(videoId);
                    editModel.filePath =  HttpUtility.UrlDecode(model.filePath);//文件路径
                    editModel.imgPath =  HttpUtility.UrlDecode(model.imgPath);//封面路径
                    editModel.videoName = HttpUtility.UrlDecode(model.videoName);//视频标题
                    bool result = videoBLL.Update(editModel);
                    return Json(new { result = result ? "success" : "error", msg = result ? "修改成功" : "修改失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { result = "error", msg = ex.Message });
            }
        }


        /// <summary>
        /// 视频删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult VideoDelete(string ids = "")
        {
            try
            {
                if (ids == "")
                {
                    return Json(new { result = "error", msg = "传入参数有误" }, JsonRequestBehavior.AllowGet);
                }
                List<int> idList =
                    ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(item => item.ToInt32()).ToList();
                var result = videoBLL.Delete(idList, Server.MapPath("/Upload"));
                return Json(new { result = result ? "success" : "error", msg = result ? "删除成功" : "删除失败" },
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { result = "error", msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }



        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="lastModifiedDate"></param>
        /// <param name="size"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult FileUpload(string id, string name, string type, string lastModifiedDate, int size,
            HttpPostedFileBase file)
        {
            try
            {
                string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
                if (Request.Files.Count == 0)
                {
                    return Json(new {jsonrpc = 2.0, error = new {code = 102, message = "保存失败"}, id = "id"});
                }

                string ex = Path.GetExtension(file.FileName);
                string filePathName = Guid.NewGuid().ToString("N") + ex;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                file.SaveAs(Path.Combine(localPath, filePathName));
                return Json(new
                {
                    result = "success",
                    filePath = "/Upload/" + filePathName
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    result = "error",
                    msg = ex.Message
                });
            }
        }
    }
}